import React, { useState, useContext, useMemo } from 'react';

import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import styles from './index.less';
import { UploadPhotoContext } from './context';

interface UploadItemProps {
  type: string;
  title: string;
  action: string;
  defaultImageUrl: string;
}

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const UploadItem = (props: UploadItemProps) => {
  const { title, type, action, defaultImageUrl } = props;
  const { uploadForm, setUploadForm } = useContext(UploadPhotoContext);
  const [loading, setLoading] = useState<boolean>(false);
  const [imageUrl, setImageUrl] = useState<string>('');

  useMemo(() => {
    setImageUrl(defaultImageUrl);
  }, [defaultImageUrl]);

  const handleChange = (info: {}) => {
    if (info.file.status === 'uploading') setLoading(true);
    if (info.file.status === 'done') {
      const { code, data, info: resInfo } = info.file.response;
      getBase64(info.file.originFileObj, (url: string) => {
        if (code) {
          message.error(`上传失败：${resInfo}`);
          return;
        }
        uploadForm[type] = data.url;
        setImageUrl(url);
        setUploadForm({ ...uploadForm });
      });
    }
  };

  const uploadButton = () => (
    <div className={styles['upload-choose']}>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className={styles['pic-upload-text']}>{title}</div>
    </div>
  );

  return (
    <Upload
      name="file"
      listType="picture-card"
      showUploadList={false}
      action={action}
      onChange={(info) => {
        handleChange(info, 0);
      }}
    >
      {imageUrl ? (
        <img src={imageUrl} alt="avatar" style={{ width: '100px', maxHeight: '100px' }} />
      ) : (
        uploadButton()
      )}
    </Upload>
  );
};

export default UploadItem;
